package com.jsyh.maidu.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.baoyz.widget.PullRefreshLayout;
import com.jsyh.maidu.R;
import com.jsyh.maidu.activity.me.CreateOrderActivity;
import com.jsyh.maidu.activity.me.LoginActivity;
import com.jsyh.maidu.config.ConfigValue;
import com.jsyh.maidu.config.SPConfig;
import com.jsyh.maidu.config.StaticVelue;
import com.jsyh.maidu.model.AttributeModel;
import com.jsyh.maidu.model.BaseModel;
import com.jsyh.maidu.model.CartGoods;
import com.jsyh.maidu.model.CartGoodsModel;
import com.jsyh.maidu.model.GoodsAttr;
import com.jsyh.maidu.model.Login;
import com.jsyh.maidu.presenter.CartGoodsPresenter;
import com.jsyh.maidu.presenter.ChangeCardPresenter;
import com.jsyh.maidu.presenter.GetAttribute;
import com.jsyh.maidu.utils.ParamPopupWindow;
import com.jsyh.maidu.utils.SPUtils;
import com.jsyh.maidu.utils.Utils;
import com.jsyh.maidu.views.CartGoodsView;
import com.jsyh.maidu.views.PersonalView;
import com.jsyh.shopping.uilibrary.adapter.listview.BaseAdapterHelper;
import com.jsyh.shopping.uilibrary.adapter.listview.QuickAdapter;
import com.jsyh.shopping.uilibrary.views.MyListView;
import com.liang.library.RoundedTransformationBuilder;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Su on 2015/10/20.
 * 商品详情中跳转购物车
 */
public class ShoppingCartActivity extends BaseActivity implements CartGoodsView,View.OnClickListener{



    private PullRefreshLayout pullRefreshLayout;
    private PullRefreshLayout pullRefreshLayout2;

    private QuickAdapter<CartGoodsModel.CartShop> mCartGoodsAdapter;

    private CartGoodsModel cartgoodsmodel;

    private CartGoodsPresenter cartGoodsPresenter;
    //购物车列表
    private MyListView mListView;
    //已登录并且购物车中有数据
    private FrameLayout mFrameLayoutLogin;
    //购物车为空，提示登录窗口
    private TableRow mTableRowToLogin;
    //所有的商品集合
    private List<CartGoods> allCartGoodsList;
    //已经选择的商品集合
    private List<CartGoods> selectCartGoodsList;
    private Button mButtonToLogin;
    private Button mButtonSettleAccounts;
    private LinearLayout ll_main;
    private LinearLayout ll_null,ll_new,ll_hot;
    private ImageView iv_back;
    TextView tv_title;

    //去结算
    private TextView mTextViewTotalPrice;

    private CheckBox mCheckBoxSelectAll;
    private GetAttribute attributepresenter;

    private  ChangeCardPresenter CHangepersenter;

    private boolean flag = true;//用来区分是首次加载还是刷新的标识

    private Transformation mTransformation;

    //网络错误用到的view
    private ViewStub mNetworStub;
    private View mNetworkErrorLayout;
    private Button mReloadRequest;

    private boolean isAllSelected=false;
    Double total=0.00;
    CartGoods DelGoods;



    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.fragment_message);
        cartGoodsPresenter = new CartGoodsPresenter(this);
        CHangepersenter=new ChangeCardPresenter(mContext,this);
        ll_main= (LinearLayout) findViewById(R.id.ll_car_main);
        ll_null= (LinearLayout) findViewById(R.id.ll_car_null);
        mButtonToLogin= (Button) findViewById(R.id.toLogin);
        mFrameLayoutLogin= (FrameLayout) findViewById(R.id.loginLayout);
        mTableRowToLogin = (TableRow) findViewById(R.id.login);
        tv_title= (TextView) findViewById(R.id.title);
        iv_back= (ImageView) findViewById(R.id.back);
        ll_hot= (LinearLayout) findViewById(R.id.ll_car_hot);
        ll_new= (LinearLayout) findViewById(R.id.ll_car_new);
        tv_title.setText("购物车");
        initPullRefreshLayout();
        initPullRefreshLayout2();
        selectCartGoodsList=new ArrayList<>();
        initTransformation();
        mListView= (MyListView) findViewById(R.id.list);
        mTextViewTotalPrice= (TextView) findViewById(R.id.total_sum);

        mCheckBoxSelectAll= (CheckBox) findViewById(R.id.select_all);
        mCheckBoxSelectAll.setChecked(false);
        mButtonSettleAccounts= (Button) findViewById(R.id.settle_accounts);
        mCheckBoxSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, final boolean b) {
                compoundButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (cartgoodsmodel==null )
                        {
                            mCheckBoxSelectAll.setClickable(false);
                            mCheckBoxSelectAll.setChecked(false);
                            return;
                        }
                        isAllSelected=true;
                        if (b)
                        {
                            for (CartGoodsModel.CartShop shop: cartgoodsmodel.getData())
                            {
                                shop.setCheckshop(true);
                            }

                        }else {
                            for (CartGoodsModel.CartShop shop: cartgoodsmodel.getData())
                            {
                                shop.setCheckshop(false);
                            }
                        }
                        mCartGoodsAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
        mButtonToLogin.setOnClickListener(this);
        mButtonSettleAccounts.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        ll_hot.setOnClickListener(this);
        ll_new.setOnClickListener(this);
    }
    //商品列表为空，下拉刷新
    private void initPullRefreshLayout2() {
        pullRefreshLayout2 = (PullRefreshLayout) findViewById(R.id.pullRefreshLayout2);
        pullRefreshLayout2.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
        pullRefreshLayout2.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pullRefreshLayout2.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        flag = false;
                        onResume();
                        pullRefreshLayout2.setRefreshing(false);
                    }
                }, 1000);
            }

            @Override
            public void onMove(boolean ismove) {

            }
        });
    }

    //商品列表下拉刷新
    private void initPullRefreshLayout() {
        pullRefreshLayout = (PullRefreshLayout) findViewById(R.id.pullRefreshLayout);
        pullRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
        pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pullRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        flag = false;
                        onResume();

                        pullRefreshLayout.setRefreshing(false);
                    }
                }, 1000);
            }

            @Override
            public void onMove(boolean ismove) {

            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        attributepresenter=new GetAttribute(mContext,this);
        mCartGoodsAdapter = new QuickAdapter<CartGoodsModel.CartShop>(mContext, R.layout.item_car_shop) {
            @Override
            protected void convert(final BaseAdapterHelper helper, final CartGoodsModel.CartShop item) {
                final CheckBox mCheckBoxSelect = (CheckBox) helper.getView().findViewById(R.id.cb_icar_shop);
                final CheckBox mCheckEdit = (CheckBox) helper.getView().findViewById(R.id.cb_icar_edit);
                MyListView lv_goods = helper.getView(R.id.lv_icar_goods);
                if (item.isCheckshop())
                {
                    mCheckBoxSelect.setChecked(true);
                }else {
                    mCheckBoxSelect.setChecked(false);
                }
                final CardGoodsAdapter adapter = new CardGoodsAdapter(mContext, R.layout.cart_goods_item, item.getGoods(), new backShopCB() {
                    @Override
                    public void backcb(int type) {
                        if (type==1)
                        {
                            mCheckBoxSelect.setChecked(false);
                            mCheckBoxSelectAll.setChecked(false);
                        }else {
                            for (CartGoods model:item.getGoods())
                            {
                                if (!model.isChexktype())
                                {
                                    break;
                                }
                                if (model==item.getGoods().get(item.getGoods().size()-1))
                                {
                                    mCheckBoxSelect.setChecked(true);
                                    for (int j=0;j<cartgoodsmodel.getData().size()-1;j++)
                                    {
                                        if (!cartgoodsmodel.getData().get(j).isCheckshop())
                                        {
                                            break;
                                        }
                                        if (cartgoodsmodel.getData().get(j)==cartgoodsmodel.getData().get(cartgoodsmodel.getData().size()-1))
                                        {
                                            mCheckBoxSelectAll.setChecked(true);
                                        }
                                    }
                                }

                            }
                        }
                    }
                });
                lv_goods.setAdapter(adapter);
                //选择商品

                mCheckBoxSelect.setText(item.getSupplier_name());

                mCheckBoxSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                        item.setCheckshop(isChecked);

                        if (isAllSelected)
                        {
                            isAllSelected=false;
                            if (isChecked)
                            {
                                item.setCheckshop(true);
                                for (int i=0;i<item.getGoods().size();i++)
                                {
                                    item.getGoods().get(i).setChexktype(true);
                                }

                            }else {
                                item.setCheckshop(false);
                                for (int i=0;i<item.getGoods().size();i++)
                                {
                                    item.getGoods().get(i).setChexktype(false);
                                }
                            }
                            adapter.notifyDataSetChanged();
                            PushCarCheckedData();
                        }else {
                            if (isChecked)
                            {

                                for (int i=0;i<item.getGoods().size();i++)
                                {
                                    item.getGoods().get(i).setChexktype(true);
                                }

                            }else {
                                for (int i=0;i<item.getGoods().size();i++)
                                {
                                    item.getGoods().get(i).setChexktype(false);
                                }
                            }

                            for (int j=0;j<cartgoodsmodel.getData().size()-1;j++)
                            {
                                if (cartgoodsmodel.getData().get(j).isCheckshop()!=isChecked)
                                {
                                    break;
                                }
                                if (cartgoodsmodel.getData().get(j)==cartgoodsmodel.getData().get(cartgoodsmodel.getData().size()-1))
                                {
                                    mCheckBoxSelectAll.setChecked(isChecked);
                                }
                            }
                            adapter.notifyDataSetChanged();
                            PushCarCheckedData();

                        }




/*
                        if (buttonView.performClick())
                        {
                            if (isChecked)
                            {

                                for (int i=0;i<item.getGoods().size();i++)
                                {
                                    item.getGoods().get(i).setChexktype(true);
                                }

                            }else {
                                for (int i=0;i<item.getGoods().size();i++)
                                {
                                    item.getGoods().get(i).setChexktype(false);
                                }
                            }
                            for (CartGoodsModel.CartShop shop:cartgoodsmodel.getData())
                            {
                                if (shop.isCheckshop()!=isChecked)
                                {
                                    break;
                                }
                                if (shop==cartgoodsmodel.getData().get(cartgoodsmodel.getData().size()-1))
                                {
                                    mCheckBoxSelectAll.setChecked(isChecked);
                                }
                            }
                            adapter.notifyDataSetChanged();
                            PushCarCheckedData();
                        }else {
                            if (isAllSelected)
                            {
                                isAllSelected=false;
                                if (isChecked)
                                {
                                    item.setCheckshop(true);
                                    for (int i=0;i<item.getGoods().size();i++)
                                    {
                                        item.getGoods().get(i).setChexktype(true);
                                    }

                                }else {
                                    item.setCheckshop(false);
                                    for (int i=0;i<item.getGoods().size();i++)
                                    {
                                        item.getGoods().get(i).setChexktype(false);
                                    }
                                }
                                adapter.notifyDataSetChanged();
                                PushCarCheckedData();
                            }

                        }*/


                    }
                });
                mCheckEdit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (!b){
                            mCheckEdit.setText("编辑");
                            for (int i=0;i<item.getGoods().size();i++)
                            {
                                item.getGoods().get(i).setLayouttype(false);
                            }

                        }else {
                            mCheckEdit.setText("完成");
                            for (int i=0;i<item.getGoods().size();i++)
                            {
                                item.getGoods().get(i).setLayouttype(true);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                });

            }

        };
        mListView.setAdapter(mCartGoodsAdapter);

    }



    /**
     * 显示购物车数据
     * @param cartGoodsModel
     */
    @Override
    public void getCartGoodsList(CartGoodsModel cartGoodsModel) {
        if (cartGoodsModel.getCode().equals("1"))
        {
            if (cartGoodsModel.getData().size()!=0)
            {
                ll_null.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
                cartgoodsmodel=cartGoodsModel;
                mCartGoodsAdapter.clear();
                mCartGoodsAdapter.addAll(cartGoodsModel.getData());
            }else {
                ll_null.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);

            }
        }

    }

    /**
     * 修改数量
     * @param baseModel
     * @param goodsIdNumber
     */

    @Override
    public void alterCartGoodsNumber(BaseModel baseModel,String goodsIdNumber) {


        if (baseModel.getCode().equals("1"))
        {
            if (DelGoods.isChexktype())
            {
                total=total+Double.valueOf(DelGoods.getGoods_price())*Double.valueOf(Integer.valueOf(goodsIdNumber)-Integer.valueOf(DelGoods.getNumber()));
                BigDecimal   big   =   new   BigDecimal(total);
                mTextViewTotalPrice.setText(big.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()+"");
            }

            DelGoods.setNumber(goodsIdNumber);
        }else {

            Utils.showToast(mContext,baseModel.getMsg());
            mCartGoodsAdapter.notifyDataSetChanged();
        }





    }

    /**
     * 删除商品
     * @param baseModel
     */

    @Override
    public void deleteCartGoods(BaseModel baseModel) {
        if (baseModel.getCode().equals("1"))
        {
            cartgoodsmodel.getData().remove(DelGoods);
            for (CartGoodsModel.CartShop shop:cartgoodsmodel.getData())
            {
                if (shop.getSupplier_id().equals(DelGoods.getSupplier_id()))
                {
                    shop.getGoods().remove(DelGoods);
                    if (shop.getGoods().size()==0)
                    {
                        cartgoodsmodel.getData().remove(shop);
                        mCartGoodsAdapter.remove(shop);
                        break;
                    }else {
                        break;
                    }

                }
            }

            mCartGoodsAdapter.notifyDataSetChanged();
        }else {

        }
    }

    @Override
    public void getAttr(AttributeModel Model, String id, final String carid) {
        final ParamPopupWindow natureWindow=new ParamPopupWindow(mContext, Model.getData().getAttribute(), id, "", "", new ParamPopupWindow.OnSubmitListener() {
            @Override
            public void submit(GoodsAttr attr) {
                DelGoods.setAttrvalue_selected(attr.getChecked());
                DelGoods.setGoods_img(attr.getImage());
                DelGoods.setGoods_price(attr.getTotal_price());
                CHangepersenter.LoadCardchange(carid,attr.getAttr_value_id());
            }
        },"");
        natureWindow.setSumGone(View.GONE);
        natureWindow.show(ll_main);
    }

    @Override
    public void returnCardchange(BaseModel model) {

        if (model.getCode().equals("1"))
        {
            mCartGoodsAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onClick(View view) {

        switch (view.getId())
        {
            case R.id.settle_accounts:
                if (selectCartGoodsList!=null && selectCartGoodsList.size()!=0)
                {
                    StaticVelue.selectGoodsList = selectCartGoodsList;
                    Intent intent = new Intent(this, CreateOrderActivity.class);
                    intent.putExtra("intentType", "2");
                    startActivity(intent);
                }



                break;
            case R.id.toLogin:
                Intent loginintent=new Intent(mContext, LoginActivity.class);
                startActivity(loginintent);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.ll_car_hot:
                Intent hintent = new Intent(mContext, GoodsListActivity.class);
                hintent.putExtra("type", ConfigValue.TYPE_HOT);
                mContext.startActivity(hintent);
                break;
            case R.id.ll_car_new:
                Intent nintent = new Intent(mContext, GoodsListActivity.class);
                nintent.putExtra("type", ConfigValue.TYPE_NEW);
                mContext.startActivity(nintent);
                break;

        }
    }

    @Override
    public void onResume() {

        Log.d("order", "onResume");

        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(mContext)) {
            switchLayout();
        } else {
            if (mNetworkErrorLayout != null) {
                mNetworkErrorLayout.setVisibility(View.GONE);
            }
            ConfigValue.DATA_KEY = (String) SPUtils.get(this, SPConfig.KEY, "");
            if (ConfigValue.DATA_KEY != null && !ConfigValue.DATA_KEY.equals("")) {
                //本地存在key
                mFrameLayoutLogin.setVisibility(View.VISIBLE);
                pullRefreshLayout2.setVisibility(View.GONE);

                mTableRowToLogin.setVisibility(View.GONE);
                cartGoodsPresenter.getCartGoodsData(this, flag);

            } else {
                //不存在key，提示需要登录
                mFrameLayoutLogin.setVisibility(View.GONE);
                pullRefreshLayout2.setVisibility(View.VISIBLE);

                mTableRowToLogin.setVisibility(View.VISIBLE);
            }
        }


        super.onResume();
    }

    /*
    无网布局
     */
    public void switchLayout() {

        mNetworkErrorLayout.setVisibility(View.VISIBLE);

        pullRefreshLayout.setVisibility(View.GONE);
        pullRefreshLayout2.setVisibility(View.GONE);

    }

    public  class CardGoodsAdapter extends QuickAdapter<CartGoods>
    {
        LinearLayout ll_msg,ll_chnum;
        backShopCB cb;

        public CardGoodsAdapter(Context context, int layoutResId, List<CartGoods> data,backShopCB cb) {
            super(context, layoutResId, data);
            this.cb=cb;
        }


        @Override
        protected void convert(final BaseAdapterHelper helper, final CartGoods item) {
            ll_msg=helper.getView(R.id.ll_icar_msg);
            ll_chnum=helper.getView(R.id.ll_icar_chnum);
            CheckBox cb_chexk=helper.getView(R.id.select_goods);

            cb_chexk.setChecked(item.isChexktype());

            if (!item.isLayouttype())
            {
                ll_chnum.setVisibility(View.GONE);
                ll_msg.setVisibility(View.VISIBLE);
            }else {
                ll_chnum.setVisibility(View.VISIBLE);
                ll_msg.setVisibility(View.GONE);
            }

            if (item.getAttrvalue_selected()==null)
            {
                helper.getView(R.id.tv_icar_nature).setVisibility(View.GONE);
            }else {
                helper.getView(R.id.tv_icar_nature).setVisibility(View.VISIBLE);
                helper.setText(R.id.tv_icar_nature,item.getAttrvalue_selected());
            }
            helper.setText(R.id.goods_name, item.getGoods_name());
            helper.setText(R.id.goods_price, "￥" + item.getGoods_price());
            //加载网络图片
            Picasso.with(mContext).load(ConfigValue.IMG_IP + item.getGoods_img()).fit().transform(mTransformation)
                    .error(R.mipmap.ic_launcher).into((ImageView) helper.getView(R.id.goods_image));

            final int goods_number = Integer.valueOf(item.getNumber());
            final String rec_id = item.getRec_id();
            String goods_price = item.getGoods_price();
            helper.setText(R.id.goods_number, goods_number + "");
            helper.setText(R.id.tv_icar_num, "X"+goods_number + "");
            helper.setText(R.id.goods_marketprice,"￥" + item.getMarket_price());
            helper.getView(R.id.tv_icar_del).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DelGoods=item;
                    cartGoodsPresenter.deleteCartGoods(mContext,item.getRec_id());
                }
            });
            helper.getView(R.id.number_sub).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DelGoods=item;
                    helper.setText(R.id.goods_number,Integer.valueOf(item.getNumber())-1+"");
                    cartGoodsPresenter.alterCartGoodsNumber(mContext,item.getRec_id(),Integer.valueOf(item.getNumber())-1);
                }
            });
            helper.getView(R.id.number_add).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DelGoods=item;
                    helper.setText(R.id.goods_number,Integer.valueOf(item.getNumber())+1+"");
                    cartGoodsPresenter.alterCartGoodsNumber(mContext,item.getRec_id(),Integer.valueOf(item.getNumber())+1);
                }
            });

            helper.getView(R.id.tv_icar_nature).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DelGoods=item;

                    attributepresenter.LaodAttribute(item.getGoods_id(),item.getRec_id());
                }
            });

            cb_chexk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, final boolean b) {

                    compoundButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (b)
                            {
                                item.setChexktype(true);
                                selectCartGoodsList.add(item);
                                total=total+Double.valueOf(item.getGoods_price())*Double.valueOf(item.getNumber());
                                cb.backcb(2);

                            }else {
                                item.setChexktype(false);
                                selectCartGoodsList.remove(item);
                                total=total-Double.valueOf(item.getGoods_price())*Double.valueOf(item.getNumber());
                                cb.backcb(1);
                            }
                            BigDecimal   big   =   new   BigDecimal(total);
                            mTextViewTotalPrice.setText(big.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()+"");
                        }
                    });

                }

            });


        }


    }
    private void initTransformation() {
        mTransformation = new RoundedTransformationBuilder()
                .cornerRadiusDp(5)
                .borderColor(Color.TRANSPARENT)
                .borderWidthDp(1)
                .oval(false)
                .build();

    }

    public void PushCarCheckedData()
    {
        selectCartGoodsList.clear();
        for (CartGoodsModel.CartShop model:cartgoodsmodel.getData())
        {
            for (CartGoods good:model.getGoods())
            {
                if (good.isChexktype())
                {
                    selectCartGoodsList.add(good);
                }
            }
        }
        figureTotal();
    }

    public void  figureTotal()
    {
        total=0.00;

        for (CartGoods good:selectCartGoodsList)
        {
            total=total+Double.valueOf(good.getNumber())*Double.valueOf(good.getGoods_price());
        }
        BigDecimal   b   =   new   BigDecimal(total);


        mTextViewTotalPrice.setText(b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()+"");


    }

    public interface backShopCB
    {
        void backcb(int type);

    }

}
